from turtle import left
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
from tkinter.scrolledtext import ScrolledText

class dataForm():
    def create_form_entry(self, label, variable):
        """Create a single form entry"""
        container = ttk.Frame(self)
        container.pack(fill=X, expand=YES, pady=5)

        lbl = ttk.Label(master=container, text=label.title(), width=10)
        lbl.pack(side=LEFT,anchor=E, padx=5)

        ent = ttk.Entry(master=container, textvariable=variable)
        ent.pack(side=LEFT, padx=5, fill=X, expand=YES)

class DataEntryForm(ttk.Frame,dataForm):

    def __init__(self,main,data=None):
        self.main=main
        self.top=main.top

        # 使弹出窗口一直处于主窗口前面
        self.top.transient(self.main.win)
        # 将top1设置为模式对话框，top1不关闭无法操作主窗口
        # self.top.grab_set()

        self.main.center_window(self.top,500,450)
        super().__init__(self.top, padding=(20, 10))
        
        self.pack(fill=BOTH, expand=YES)

        if data:
            self.name = ttk.StringVar(value=data[1]) #
            self.time = ttk.StringVar(value=data[2])
            self.source = ttk.StringVar(value=data[3])
            self.description = ttk.StringVar(value=data[4])
            self.state = ttk.IntVar(value=int(data[5]))
            self.id = data[0]
        else:
        # form variables
            self.name = ttk.StringVar(value="") #
            self.time = ttk.StringVar(value="")
            self.source = ttk.StringVar(value="")
            self.description = ttk.StringVar(value="")
            self.state = ttk.IntVar(value=1)
            self.id=-1
        # 名称、时间、描述、状态、资源

        # form entries
        self.create_form_entry("番剧名", self.name)
        self.create_form_entry('时间',self.time)
        self.create_state()
        # self.create_form_entry("资源", self.source)
        self.create_source()
        # self.create_form_entry("描述", self.description)
        self.create_desc()

        self.create_buttonbox()

    def create_desc(self):
        container = ttk.Frame(self)
        container.pack(fill=X, expand=YES, pady=5)

        lbl = ttk.Label(master=container, text='描述', width=10)
        lbl.pack(side=LEFT,anchor=E, padx=5)

        self.descInput = ScrolledText(
            master=container,height=5,
            font = ( "微软雅黑" , 9),wrap=WORD
        )
        self.descInput.pack(side=LEFT, padx=5,fill=BOTH)
        self.descInput.insert(END, self.description.get())

    def create_source(self):
        container = ttk.Frame(self)
        container.pack(fill=X, expand=YES, pady=5)

        lbl = ttk.Label(master=container, text='资源', width=10)
        lbl.pack(side=LEFT,anchor=E, padx=5)

        self.sourceInput = ScrolledText(
            master=container,height=5,
            font = ( "微软雅黑" , 9),wrap=WORD
        )
        self.sourceInput.pack(side=LEFT, padx=5,fill=BOTH)
        self.sourceInput.insert(END, self.source.get())

        # ent = ttk.Entry(master=container, textvariable=variable)
        # ent.pack(side=LEFT, padx=5, fill=X, expand=YES)



    # def create_time(self):
    #     container = ttk.Frame(self)
    #     container.pack(fill=X, expand=YES, pady=5)

    #     lbl = ttk.Label(master=container, text='时间', width=10)
    #     lbl.pack(side=LEFT,anchor=E, padx=5)

    #     timeBox=ttk.Combobox(
    #         master=container,
    #         values=['一', '二', '三', '四', '五', '六', '七']
    #     )
    #     timeBox.current(0)
    #     timeBox.pack(side=LEFT,expand=True)
    #     print(timeBox.get()) #打印 一 二

    def create_state(self):
        container = ttk.Frame(self)
        container.pack(fill=X, expand=YES, pady=5)

        lbl = ttk.Label(master=container, text='状态', width=10,)
        lbl.pack(side=LEFT,anchor=E, padx=5)

        ttk.Radiobutton(
            master=container, 
            text="更新", 
            variable=self.state, 
            value=1
        ).pack(side=LEFT, padx=5)

        ttk.Radiobutton(
            master=container, 
            text="完结", 
            variable=self.state, 
            value=0
        ).pack(side=LEFT, padx=5, fill=X, expand=YES)

    def create_buttonbox(self):
        """Create the application buttonbox"""
        container = ttk.Frame(self)
        container.pack(fill=X, expand=YES, pady=(15, 10))

        sub_btn = ttk.Button(
            master=container,
            text="提交",
            command=self.on_submit,
            bootstyle=SUCCESS,
            width=6,
        )
        sub_btn.pack(side=RIGHT, padx=5)

        cnl_btn = ttk.Button(
            master=container,
            text="取消",
            command=self.on_cancel,
            bootstyle=DANGER,
            width=6,
        )
        cnl_btn.pack(side=RIGHT, padx=5)

        
        
        # sub_btn.focus_set()

    def on_submit(self):
        '''
        提交
        '''
        if self.id==-1:

            data=[self.name.get(),self.time.get(),self.sourceInput.get('1.0', 'end-1c'),self.descInput.get('1.0', 'end-1c'),str(self.state.get())]
        else:
            data=[self.id,self.name.get(),self.time.get(),self.sourceInput.get('1.0', 'end-1c'),self.descInput.get('1.0', 'end-1c'),str(self.state.get())]
        if self.main.fanjuTab.edit_data(data):
            self.on_cancel()

    def on_cancel(self):
        """
        退出
        """
        self.main.fanjuTab._top_close()


from tkinter.filedialog import askopenfilename
class applicationForm(ttk.Frame,dataForm):

    def __init__(self,main,data=None):
        self.main=main
        self.top=main.top

        # 使弹出窗口一直处于主窗口前面
        self.top.transient(self.main.win)
        # 将top1设置为模式对话框，top1不关闭无法操作主窗口
        # 开启对话模式，仅能操作该窗口，不关闭无法操作其他窗口
        # self.top.grab_set()

        self.main.center_window(self.top,450,400)
        super().__init__(self.top, padding=(20, 10))
        
        self.pack(fill=BOTH, expand=YES)

        if data:
            self.name = ttk.StringVar(value=data[1]) #
            self.path = ttk.StringVar(value=data[2])
            self.state = ttk.IntVar(value=int(data[3]))
            self.id = data[0]
        else:
        # form variables
            self.name = ttk.StringVar(value="") #
            self.path = ttk.StringVar(value="")
            self.state = ttk.IntVar(value=1)
            self.id=-1

        # form entries
        self.create_form_entry("名称", self.name)
        self.chose_file('路径',self.path)
        self.create_state()

        self.create_buttonbox()

    def create_state(self):
        container = ttk.Frame(self)
        container.pack(fill=X, expand=YES, pady=5)

        lbl = ttk.Label(master=container, text='状态', width=10)
        lbl.pack(side=LEFT,anchor=E, padx=5)

        ttk.Radiobutton(
            master=container, 
            text="是", 
            variable=self.state, 
            value=1
        ).pack(side=LEFT, padx=5)

        ttk.Radiobutton(
            master=container, 
            text="否", 
            variable=self.state, 
            value=0
        ).pack(side=LEFT, padx=5, fill=X, expand=YES)

    def chose_file(self,label,variable):
        container = ttk.Frame(self)
        container.pack(fill=X, expand=YES, pady=5)

        lbl = ttk.Label(master=container, text=label.title(), width=10)
        lbl.pack(side=LEFT,anchor=E, padx=5)

        ent = ttk.Entry(master=container, textvariable=variable)
        ent.pack(side=LEFT, padx=7)

        sub_btn = ttk.Button(
            master=container,
            text="选择文件",
            command=self.file,
            bootstyle=SUCCESS,
            width=8,
        )
        sub_btn.pack(side=LEFT, padx=3)


    def file(self):
        if self.path.get():
            path=askopenfilename(initialdir=os.path.dirname(self.path.get()))
        else:
            path= askopenfilename()
        if path and len(path)>0:
            self.path.set(path)
            if not  self.name.get():
                self.name.set(os.path.split(path)[1].split(".")[0])

    def create_buttonbox(self):
        """Create the application buttonbox"""
        container = ttk.Frame(self)
        container.pack(fill=X, expand=YES, pady=(15, 10))

        sub_btn = ttk.Button(
            master=container,
            text="提交",
            command=self.on_submit,
            bootstyle=SUCCESS,
            width=6,
        )
        sub_btn.pack(side=RIGHT, padx=5)

        cnl_btn = ttk.Button(
            master=container,
            text="取消",
            command=self.on_cancel,
            bootstyle=DANGER,
            width=6,
        )
        cnl_btn.pack(side=RIGHT, padx=5)

        
        
        # sub_btn.focus_set()

    def on_submit(self):
        '''
        提交
        '''
        if self.id==-1:

            data=[self.name.get(),self.path.get(),str(self.state.get())]
        else:
            data=[self.id,self.name.get(),self.path.get(),str(self.state.get())]
        if self.main.applicationTab.edit_data(data):
            self.on_cancel()

    def on_cancel(self):
        """
        退出
        """
        self.main.applicationTab._top_close()


'''
背景图
'''
from PIL import ImageTk
from PIL import Image
import os,getpass

class BackgroundForm(ttk.Frame):

    def __init__(self,main,state=0):
        '''
        state 是否带解屏功能 0  有 1 没有
        '''
        self.main=main
        self.closeWin=main.closeWin


        im_root = self.OnEraseBack()  #获取图片
        self.label=ttk.Label(self.closeWin, text='窗口', image=im_root,border=0)
        self.label.image=im_root
        self.label.pack()

        ttk.Button(self.closeWin,text='解除',command=self.main.active_close_win).place(relx=0,rely=0)
        
        # ttk.Button(self.closeWin,text='解除').place(relx=0.5,rely=0.5,anchor=CENTER)
        #强制锁屏
        state=1
        if state==0:
            ttk.Button(self.closeWin,text='解除',command=self.main.active_close_win).place(relx=0,rely=0)

    def formatImg(self,img):
        '''
        重置图片宽高
        '''
        width = self.main.win.winfo_screenwidth()
        height = self.main.win.winfo_screenheight()

        num=0
        try:
            img =Image.open(img)
        except:
            self.main.log.error("报错信息：",exc_info = 1)
            img =Image.open(self.main.path+"/image/default.jpg")

        W,H= img.size[0],img.size[1]
            
        if W > H:
            NewW = width
            NewH = width * H / W
        else:
            NewH = height
            NewW = height * W / H
        img = img.resize((int(NewW),int(NewH)))

        img = ImageTk.PhotoImage(img)
        return img

    def OnEraseBack(self):
        bgkPath=self.main.path+"/image/bgk/"
        
        fileList=[]
        if not os.path.exists(bgkPath):
            os.mkdir(bgkPath)
        else:
            fileList=self.foundFile(bgkPath)

        img=None
        if len(fileList)>0:

            import random
            index=random.randint(0,len(fileList))
            if index==len(fileList):
                index-=1
             
            img=fileList[index]
        else:
            img="C:\\Users\\"+getpass.getuser()+"\\AppData\\Roaming\\Microsoft\\Windows\\Themes\\TranscodedWallpaper"
        
        return self.formatImg(img)

    def foundFile(self,sourceDir,childFound=0):
        '''
        获取目录下文件，不包含子目录
        args:
            dir:文件目录
            fileNameEnd:文件名结尾
            childFound:是否扫描子目录，0 不扫描（默认），1 扫描
        '''
        if not sourceDir.endswith("/"):
            sourceDir+="/"

        list=[]
        for top,dirs,nondirs in os.walk(sourceDir):
            if childFound ==0 and top != sourceDir:       #仅处理当前目录
                continue
            
            for item in nondirs:
                file=sourceDir+item   #得到文件
                list.append(file)
        
        return list


class SetForm(ttk.Frame):

    def __init__(self,main,data=None):
        self.main=main
        super().__init__(main.notebook, padding=(20, 10))
        self.init()

    def init(self):
        '''
        基础布局
        '''
        #清空组件
        for widget in self.winfo_children():
            widget.destroy()

        # 添加组件
        two_finger_gest = ttk.Labelframe(
            master=self,
            text='基础设置',
            padding=10
        )
        two_finger_gest.pack(side=TOP, fill=BOTH)
        
        self.start = ttk.IntVar(value=self.main.data['start']) 
        self.step = ttk.IntVar(value=self.main.data['step']) 
        self.stateValue = ttk.IntVar(value=self.main.data['state'])
        self.showMain = ttk.IntVar(value=self.main.data['showMain'])
        self.openIcon = ttk.IntVar(value=self.main.data['openIcon'])

        self.create_form_entry(two_finger_gest,"开始时间", self.start)
        self.create_form_entry(two_finger_gest,"结束时间", self.step)
        self.create_state(two_finger_gest,'开启锁屏',{'开启':0,'关闭':1},self.stateValue)
        
        self.create_state(two_finger_gest,'开启托盘',{'开启':0,'关闭':1},self.openIcon)
        if self.main.data['openIcon'] ==0:
            self.create_state(two_finger_gest,'显示主窗口',{'开启':0,'关闭':1},self.showMain)
        self.create_buttonbox(two_finger_gest)

    def create_form_entry(self,master, label, variable):
        '''
        创建输入表单
        '''
        container = ttk.Frame(master)
        container.pack(fill=X, expand=YES, pady=5)

        lbl = ttk.Label(master=container, text=label.title(), width=10)
        lbl.pack(side=LEFT,anchor=E, padx=5)

        ent = ttk.Entry(master=container, textvariable=variable)
        ent.pack(side=LEFT, padx=5, fill=X, expand=YES)
    
    def create_state(self,master,text,relation,varibale):
        container = ttk.Frame(master)
        container.pack(fill=X, expand=YES, pady=5)

        lbl = ttk.Label(master=container, text=text, width=10)
        lbl.pack(side=LEFT,anchor=E, padx=5)

        size=len(relation)-1
        for index,one in  enumerate(relation):
            if index!=size:
                ttk.Radiobutton(
                    master=container, 
                    text=one, 
                    variable=varibale, 
                    value=relation[one]
                ).pack(side=LEFT, padx=5)
            else:
                ttk.Radiobutton(
                    master=container, 
                    text=one, 
                    variable=varibale, 
                    value=relation[one]
                ).pack(side=LEFT, padx=5, fill=X, expand=YES)

    def create_buttonbox(self,master):
        '''
        创建提交
        '''
        container = ttk.Frame(master)
        container.pack(fill=X, expand=YES, pady=(15, 10))

        sub_btn = ttk.Button(
            master=container,
            text="确定",
            command=self.on_submit,
            # bootstyle=SUCCESS,
            width=6,
        )
        sub_btn.pack(side=RIGHT, padx=5)

    def on_submit(self):
        '''
        提交
        '''
        data={"start":self.start.get(),"step":self.step.get(),"state":self.stateValue.get(),"showMain":self.showMain.get(),"openIcon":self.openIcon.get()}
        self.main.changeValue(data)
